const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 1002 });

const clients = {};

wss.on('connection', (client) => {
  client.on('message', (message) => {
    client.send(`${message}nn`);
  });

  client.on('close', () => {
    // 从map中移除该client
    delete clients[client.protocol];
    console.log('客户端关闭，剩余连接数为：', wss.clients.size);
  });

  // 将client对象放入map，以client.protocol作为key
  clients[client.protocol] = client;

  console.log(
    '客户端建立连接，总连接数为：',
    wss.clients.size,
    client.protocol,
  );
});

module.exports = {
  clients,
};
